﻿using System.Collections.Generic;
using System.Net.Mail;
using Commands.Settings;
using System.Diagnostics;

namespace Commands
{
    /// <summary>
    /// TODO: Output to console, to parameter.
    /// </summary>
    class Mailer : IMailer
    {
        public Mailer(MailSettings credentilas)
        {
            _credentials = credentilas;
        }

        // TODO implement
        public void SendZippedMail(string to, string subject, IEnumerable<string> attachPaths, string body)
        {
        }

        public void SendMail(string to, string subject, IEnumerable<string> attachPaths, string body)
        {
            Debug.Assert(!System.String.IsNullOrEmpty(to), "to is null or empty.");
            Debug.Assert(attachPaths != null, "attachPaths is null.");

            string from = _credentials.MailAddress;

            MailMessage message = new MailMessage(from, to, subject, body);

            foreach (var path in attachPaths)
                message.Attachments.Add(new Attachment(path));

            SmtpClient client = new SmtpClient(_credentials.SmtpServer);
            client.Port = _credentials.SmtpPort;
            client.Credentials = _credentials;

            client.Send(message);

            message.Attachments.Dispose();
        }

        public int MaxAttachSize
        {
            get { return _credentials.MaxAttachSize; }
        }

        public void SendMail(string to, string subject, string attachPath, string body)
        {
            SendMail(to, subject, new []{attachPath} ,body);
        }

        public void SendMail(string to, string subject, string body)
        {
            string filename = null;

            if (body.Length > MAX_BODY_SIZE)
            {
                filename = FilesHelper.SaveToTextFile(subject, body);
                body = string.Empty;
            }

            SendMail(to, filename, filename, body);
        }

        private const int MAX_BODY_SIZE = 300;

        private MailSettings _credentials;
    }
}
